package com.xiaotao.interceptor;

import com.alibaba.fastjson.JSONObject;
import com.xiaotao.util.JwtUtil;
import com.xiaotao.util.ResponseEnum;
import com.xiaotao.util.ResponseUtil;
import com.xiaotao.util.UserUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@Component
@Slf4j
public class JwtInterceptor implements HandlerInterceptor {
    @Resource
    private StringRedisTemplate stringRedisTemplate;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        response.setContentType("application/json;charset=utf-8");
        String token = request.getHeader("token");
        if (token == null) {
            log.error("账号为空");
            response.getWriter().write(JSONObject.toJSONString(ResponseUtil.getError(400, "未登录")));
            return false;
        }
        try {
            //修改token
            Integer userId = UserUtil.UserContext();
            String token1 = stringRedisTemplate.opsForValue().get("token" + userId);
            if (token1 == null) {
                log.error("账号失效");
                response.getWriter().write(JSONObject.toJSONString(ResponseUtil.get(ResponseEnum.USER_6)));
                return false;
            }
            boolean verify = JwtUtil.verify(token);
            if (!verify) {
                log.error("账号无效");
                response.getWriter().write(JSONObject.toJSONString(ResponseUtil.getError(400, "账号无效")));
                return false;
            }
        } catch (Exception e) {
            log.error("token无效");
            response.getWriter().write(JSONObject.toJSONString(ResponseUtil.getError(400, "账号无效")));
            return false;
        }
        return true;
    }
}
